package services

import (
    "context"
)

type Operation struct {
    Execute   func() error
    Rollback  func() error
}

type Transaction struct {
    ctx        context.Context
    operations []Operation
}

type TransactionService struct {
    ctx context.Context
}

func NewTransactionService(ctx context.Context) *TransactionService {
    return &TransactionService{ctx: ctx}
}

func (s *TransactionService) NewTransaction() *Transaction {
    return &Transaction{
        ctx:        s.ctx,
        operations: make([]Operation, 0),
    }
}

func (t *Transaction) Add(execute func() error, rollback func() error) {
    t.operations = append(t.operations, Operation{
        Execute:  execute,
        Rollback: rollback,
    })
}

func (t *Transaction) Execute() error {
    var executedOps []Operation

    for _, op := range t.operations {
        if err := op.Execute(); err != nil {
            // 执行回滚
            for i := len(executedOps) - 1; i >= 0; i-- {
                executedOps[i].Rollback()
            }
            return err
        }
        executedOps = append(executedOps, op)
    }

    return nil
}
